package com.xhsd.zlong.generatecode.model.impl.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;


public class DatabaseUtil  {
	public final String DIRVER_CLASS_NAME="com.mysql.jdbc.Driver";
	
	private String url;
	
	private String username="root";
	
	private String passwd="root";
	
	private DatabaseUtil(String url,String username,String passwd) throws ClassNotFoundException{
		this.url=url;
		
		if(username!=null) this.username=username;
		
		if(passwd!=null) this.passwd=passwd;
		
		Class.forName(DIRVER_CLASS_NAME);
	}
	
	/**
	 * @param url jdbc:mysql://localhost/linetracker?characterEncoding=GBK&zeroDateTimeBehavior=convertToNull
	 * @param username 默认root
	 * @param passwd 默认为root
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static DatabaseUtil getInstance(String url,String username,String passwd) throws ClassNotFoundException{		
		
		return new DatabaseUtil(url,username,passwd);
		
	}
	

	
	
	public Connection getConnection() throws SQLException{
		
		return DriverManager.getConnection(url, username, passwd);
		
	}
	
	
	public Statement getStatement() throws SQLException{
		
		Connection connection=getConnection();
		try{
		
			return getConnection().createStatement();
		
		}catch (SQLException e){
			
			throw e;
			
		}finally{
			
			connection.close();
			
		}
	}
	

	/**
	 * 将查询出来的结果封装到map中
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public List<Map<String,Object>> select(String sql) throws SQLException{
        
	        Statement statement=getStatement();
	        
			ResultSet rs = statement.executeQuery(sql);
			
	        try{
	        	return BuildMap.build(rs);
	        }
	        catch (SQLException e) {
	
	        	throw e;
	        	
			}finally{
				
				rs.close();
			}
	}

}
